package com.birdboot.core;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

/**
 * 该线程的任务是与指定客户端完成HTTP交互
 */
public class ClientHandler implements Runnable{
    private Socket socket;

    public  ClientHandler(Socket socket){
        this.socket = socket;
    }

    @Override
    public void run() {
        // 1、解析请求
        try {
            InputStream in = socket.getInputStream();
            int d;
            StringBuilder builder = new StringBuilder();// 保存拼接后的字符串
            char cur = 'a',pre = 'a';// cur表示本次读取的字符，pre表示上次读取的字符
            while ((d=in.read())!=-1) {
                cur = (char) d;
                if (pre==13 && cur==10){
                    break;
                }
                builder.append(cur);
                pre=cur;
            }
            String line =  builder.toString().trim();
            System.out.println("请求行："+line);
            // 将请求行中的请求方式，抽象路径，协议版本分别解析出来
            String method;
            String uri;
            String protocol;
            String[] data = line.split("\\s");
            method = data[0];
            uri = data[1];
            protocol = data[2];
            System.out.println("method:"+method);
            System.out.println("uri:"+uri);
            System.out.println("protocol:"+protocol);
            // 2、处理请求



            // 3、发送响应




        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                //遵循Http协议要求，一问一答后关闭连接，finally里面的代码每次运行后都要运行
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
